package com.arvato.admin01.component;

import com.arvato.admin01.Util.JsonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

@Component
public class RedisLock {

    @Autowired
    private StringRedisTemplate redisTemplate;


    public boolean lock1(String key, String value){
        // setIfAbsent 相当于 jedis中的setnx,如果能赋值就返回true,如果已经有值了，就返回false,
        //即是，第一次， 这个key还没有被赋值的时候
        if (redisTemplate.opsForValue().setIfAbsent(key, value)){
            return true;
        }
        String current_value = redisTemplate.opsForValue().get(key);
        if (!JsonUtil.Object2String(current_value).equals("")
               //超时
                &&Long.parseLong(current_value)<System.currentTimeMillis()){
            String old_value = redisTemplate.opsForValue().getAndSet(key, value);
            if (!JsonUtil.Object2String(old_value).equals("")&& old_value.equals(current_value)){
              return true;
            }

        }
       return false;
    }

     // 解锁
    public void unlock(String key, String value){
    try{
        if (JsonUtil.Object2String(redisTemplate.opsForValue().get(key)).equals(value)){
            redisTemplate.opsForValue().getOperations().delete(key);
        }
    }catch (Exception e){
        e.printStackTrace();
      }
    }


}
